package com.xhu.collegestudentrentalsystem.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.xhu.collegestudentrentalsystem.module.user.entity.User;
import com.xhu.collegestudentrentalsystem.module.user.service.impl.UserServiceImpl;
import com.xhu.collegestudentrentalsystem.util.CookieUtil;
import com.xhu.collegestudentrentalsystem.util.HostHolder;
import com.xhu.collegestudentrentalsystem.util.JWTUtils;
import com.xhu.collegestudentrentalsystem.util.constant.EntityProperty;
import com.xhu.collegestudentrentalsystem.util.constant.KeyMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhu huilin
 * @date 2023/3/3 22:19
 *
 *  处理浏览器请求拦截操作
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger logger= LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private JWTUtils jwtUtils;

    /**
     * 请求刚发起，未到控制器方法处，执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在前端的请求中获取JWT，如果有用户信息，则已登录，否则未登录
        String token = CookieUtil.getValue(request, "token");
        if(token != null){
            // 解析JWT令牌
            try {
                jwtUtils.verify(token);
            }catch (JWTVerificationException e){
                logger.error(e.getMessage(), e.getCause());
                return false;
            }

            // 获取用户信息，存放在hostHolder里
            String username = jwtUtils.getValue(token, EntityProperty.user.USERNAME, String.class);
            String role = jwtUtils.getValue(token, EntityProperty.user.USER_ROLE, String.class);
            String email = jwtUtils.getValue(token, EntityProperty.user.USER_EMAIL, String.class);
            User user = userService.findUserByEmail(email);
            // User user = userService.findUserByUsername(username);
            hostHolder.setUser(user);
        }
        return true;
    }

    /**
     * 控制器方法执行后，返回到模板引擎之前，执行
     *      1. 判断用户是否登录（登录成功包含用户信息，否则没有）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null){
            modelAndView.addObject(KeyMsg.user.LOGIN_USER_DATA, user);
        }
    }

    /**
     * 整个请求完成后，执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
    }
}
